<template>
    <el-button link @click="closeWindow" style="float: right;">
        <el-icon>
            <Close />
        </el-icon>
    </el-button>
    <div class="download-page">
        <h3><el-icon>
                <Lightning />
            </el-icon> 下载队列</h3>

        <!-- <div class="add-box">
            <input v-model="url" placeholder="输入下载链接" @keyup.enter="addDownload" />
            <button @click="addDownload">开始下载</button>
        </div> -->

        <div class="task-container">
            <div v-for="task in tasks" :key="task.id" class="task-card">
                <div class="task-header">
                    <div class="task-title">
                        <el-icon class="file-icon">
                            <Document />
                        </el-icon>
                        <span class="filename">{{ task.softName }}</span>
                    </div>
                    <div class="task-status" :class="task.state">
                        {{ statusText(task) }}
                    </div>
                </div>

                <div class="task-details">
                    <div class="progress-info">
                        <span class="progress-text">{{ task.percentage }}%</span>
                        <span class="size-text">{{ formatBytes(task.receivedBytes) }} / {{ formatBytes(task.totalBytes)}}</span>
                    </div>
                    <div class="speed-info">
                        速度: {{ formatSpeed(task.speed) }}
                    </div>
                </div>

                <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: task.percentage + '%' }" :class="task.state"></div>
                </div>

                <div class="task-actions">
                    <button v-if="task.state === 'progress'" @click="pause(task.id)" class="action-btn pause-btn"
                        title="暂停">
                        <el-icon>
                            <VideoPause />
                        </el-icon>
                    </button>
                    <button v-else @click="resume(task.id)" class="action-btn resume-btn" title="继续">
                        <el-icon>
                            <VideoPlay />
                        </el-icon>
                    </button>
                    <button @click="remove(task.id)" class="action-btn cancel-btn" title="取消">
                        <el-icon>
                            <CircleClose />
                        </el-icon>
                    </button>
                </div>
            </div>
        </div>
        <div v-if="tasks.length === 0" class="empty-state">
            <el-icon class="empty-icon">
                <Box />
            </el-icon>
            <p>暂无下载任务</p>
        </div>
    </div>
</template>

<script>
    import { Lightning } from '@element-plus/icons-vue';
    import { useWindowStore } from '/src/stores/windowStore';
    import { ipcRenderer } from 'electron';
    export default {
        name: 'DownloadPage',
        data() {
            return {
                tasks: [],
                url: '',
                removeProgress: null,
                removeSpeed: null,
                removeComplete: null,
                removeError: null
            };
        },
        setup() {
            const windowStore = useWindowStore();
            return { windowStore };
        },
        methods: {
            formatBytes(bytes) {
                if (bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            },
            formatSpeed(bps) {
                return this.formatBytes(bps) + '/s';
            },
            statusText(task) {
                return task.state === 'completed' ? '已完成' :
                    task.state === 'paused' ? '已暂停' : '下载中';
            },
            // async addDownload() {
            //     const url = this.url.trim();
            //     if (!url) return;
            //     // 使用更通用的默认下载路径
            //     const path = `http://localhost:8081/Downloads/download2?type=caxclient&fileName=${url}`;
            //     const id = Date.now().toString();
            //     const result = await ipcRenderer.invoke('download:start', { id, url: path, softName: '测试名称' });
            //     if (result.success) {
            //         this.tasks.push({
            //             id,
            //             url: path,
            //             softName: decodeURIComponent(path.split('/').pop().split('?')[0]) || '未知文件',
            //             state: 'progress',
            //             receivedBytes: 0,
            //             totalBytes: 0,
            //             percentage: 0,
            //             speed: 0
            //         });
            //     } else {
            //         alert('下载失败: ' + result.error);
            //     }
            //     this.url = '';
            // },
            async pause(id) {
                await ipcRenderer.invoke('download:pause', id);
                const task = this.tasks.find(t => t.id === id);
                if (task) task.state = 'paused';
            },
            async resume(id) {
                await ipcRenderer.invoke('download:resume', id);
            },
            async remove(id) {
                await ipcRenderer.invoke('download:cancel', id);
                this.tasks = this.tasks.filter(t => t.id !== id);
            },
            async closeWindow() {
                ipcRenderer.send('download:close');
            }
        },
        mounted() {
            console.log('注册 IPC 事件监听...');
            // 监听下载事件 - 使用 on 而不是 send
            this.downloadStartListener = (event, data) => {
                data.state = 'progress';
                console.log('下载开始:', data);
                // 处理下载开始事件
                this.tasks.push(data);
            };
            ipcRenderer.on('download:start', this.downloadStartListener);
            this.downloadProgressListener = (event, data) => {
                console.log('下载进度:', data);
                const task = this.tasks.find(t => t.id === data.id);
                if (task) {
                    task.receivedBytes = data.receivedBytes;
                    task.totalBytes = data.totalBytes;
                    task.percentage = data.percentage;
                }
            };
            ipcRenderer.on('download:progress', this.downloadProgressListener);
            this.downloadSpeedListener = (event, data) => {
                console.log('下载速度:', data);
                const task = this.tasks.find(t => t.id === data.id);
                if (task) task.speed = data.speed;
            };
            ipcRenderer.on('download:speed', this.downloadSpeedListener);
            this.downloadCompleteListener = (event, data) => {
                console.log('下载完成:', data);
                const task = this.tasks.find(t => t.id === data.id);
                if (task)
                    if (task) {
                        task.state = 'completed';
                        task.receivedBytes = data.size;
                        task.totalBytes = data.size;
                        task.percentage = 100;
                    }
                this.windowStore.tasks.push(task);
                //回传列表消息
                ipcRenderer.invoke('download-status', {id: data.id, status: task.state});
            };
            ipcRenderer.on('download:complete', this.downloadCompleteListener);
            this.downloadErrorListener = (event, data) => {
                console.log('下载错误:', data);
                this.tasks = this.tasks.filter(t => t.id !== data.id);
                //回传列表消息
                ipcRenderer.invoke('download-status', {id: data.id, status: 'failed'});
            };
            ipcRenderer.on('download:error', this.downloadErrorListener);
            
        },
        beforeUnmount() {
            // 清理事件监听器
            if (this.downloadStartListener) {
                ipcRenderer.removeListener('download:start', this.downloadStartListener);
            }
            if (this.downloadProgressListener) {
                ipcRenderer.removeListener('download:progress', this.downloadProgressListener);
            }
            if (this.downloadSpeedListener) {
                ipcRenderer.removeListener('download:speed', this.downloadSpeedListener);
            }
            if (this.downloadCompleteListener) {
                ipcRenderer.removeListener('download:complete', this.downloadCompleteListener);
            }
            if (this.downloadErrorListener) {
                ipcRenderer.removeListener('download:error', this.downloadErrorListener);
            }
        }
    };
</script>
<style scoped>
    /* 样式保持不变 */
    .download-page {
        padding: 20px;
        max-width: 1000px;
        margin: 0 auto;
    }
</style>
<!-- <style scoped>
    .add-box {
        display: flex;
        gap: 10px;
        margin-bottom: 24px;
    }

    .add-box input {
        flex: 1;
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
    }

    .add-box button {
        padding: 0 20px;
        background: #007bff;
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
    }

    .add-box button:hover {
        background: #0069d9;
    }
</style> -->
<style scoped>
    .task-container {
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .task-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        transition: box-shadow 0.3s;
        border: 1px solid #ebeef5;
    }

    .task-card:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    .task-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
    }

    .task-title {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 16px;
        font-weight: 500;
        color: #303133;
    }

    .file-icon {
        color: #409eff;
        font-size: 20px;
    }

    .filename {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 300px;
    }

    .task-status {
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 4px;
        font-weight: 500;
    }

    .task-status.progress {
        background-color: #ecf5ff;
        color: #409eff;
    }

    .task-status.paused {
        background-color: #fdf6ec;
        color: #e6a23c;
    }

    .task-status.completed {
        background-color: #f0f9eb;
        color: #67c23a;
    }

    .task-details {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;
        font-size: 13px;
        color: #606266;
    }

    .progress-info {
        display: flex;
        gap: 10px;
    }

    .progress-text {
        font-weight: 600;
        color: #303133;
    }

    .progress-bar {
        width: 100%;
        height: 8px;
        background-color: #ebeef5;
        border-radius: 4px;
        overflow: hidden;
        margin-bottom: 16px;
    }

    .progress-fill {
        height: 100%;
        transition: width 0.3s ease;
        border-radius: 4px;
    }

    .progress-fill.progress {
        background: linear-gradient(90deg, #409eff, #53a8ff);
    }

    .progress-fill.paused {
        background: linear-gradient(90deg, #e6a23c, #ebb563);
    }

    .progress-fill.completed {
        background: linear-gradient(90deg, #67c23a, #85ce61);
    }

    .task-actions {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    .action-btn {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        border: none;
        background: #f5f7fa;
        color: #909399;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
    }

    .action-btn:hover {
        transform: scale(1.1);
    }

    .action-btn.pause-btn:hover {
        background: #fdf6ec;
        color: #e6a23c;
    }

    .action-btn.resume-btn:hover {
        background: #ecf5ff;
        color: #409eff;
    }

    .action-btn.cancel-btn:hover {
        background: #fef0f0;
        color: #f56c6c;
    }

    .empty-state {
        text-align: center;
        padding: 40px 0;
        color: #909399;
    }

    .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        color: #c0c4cc;
    }

    .empty-state p {
        font-size: 16px;
        margin: 0;
    }
</style>